//
//  LSZRefreshControl.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/15.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
//控件的高度
private let LSZRefreshControlHeight: CGFloat = 50

//下拉刷新的枚举类型
enum CZRefreshControlState: Int {
//    下拉刷新的状态
    case Normal = 0
//    松手就刷新的状态
    case Pulling = 1
//    正在刷新
    case Refreshing = 2
}
//自定义下拉刷新的控件
class LSZRefreshControl: UIControl {
//    当前下拉刷新的状态
    var refreshState: CZRefreshControlState = .Normal{
        didSet{
            
            switch refreshState {
            case .Normal:
                
                messageLabel.text = "下拉刷新"
//                显示箭头,关闭风火轮
                iconImageView.hidden = false
                
//                停止风火轮会隐藏这个视图
                indicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                
//                oldValue是上一次存储的值
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= LSZRefreshControlHeight
                    })
                }
                
            case .Pulling:
                
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
//                内容设置正在刷新,箭头隐藏,风火轮开启
                messageLabel.text = "正在刷新..."
                iconImageView.hidden = true
                indicatorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += LSZRefreshControlHeight
                })
                
                
                //  通知外界进行加载数据, 发送事件
                sendActionsForControlEvents(.ValueChanged)
                
            }
            
        }
    }
    //  当前滚动视图
    var currentScrollView: UIScrollView?
    // MARK: 懒加载控件
//    下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
//    内容Label
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.grayColor()
        label.text = "下拉刷新"
        return label
    }()
//    风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    添加控件设置约束
    private func setUpUI(){
        backgroundColor = RandomColor()
        
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
//        使用系统的约束进行布局
//        使用手动布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false

        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
   
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY , relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
    
    }
    
//    将要添加到那个父控件的时候去调用
    override func willMoveToSuperview(newSuperview: UIView?) {
//        判断父控件是否能够滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
//        代码执行到这里说明视图是可以滚动的
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: LSZRefreshControlHeight)
        self.frame.origin.y = -LSZRefreshControlHeight
        
//        使用kvo监听父控件的滚动
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrollView = scrollView
    }
    
//    kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(currentScrollView?.contentOffset.y);
        
//       如果有就执行,没有就直接返回
        guard let scrollView = currentScrollView else {
            return
        }
        
//       拖动状态
        if scrollView.dragging {
            if scrollView.contentOffset.y < -(scrollView.contentInset.top + LSZRefreshControlHeight) && refreshState == .Normal{
                refreshState = .Pulling
            }else if scrollView.contentOffset.y >= -(scrollView.contentInset.top + LSZRefreshControlHeight) && refreshState == .Pulling {
                refreshState = .Normal
            }
            
        }else {
//         松手状态
            if refreshState == .Pulling {
                refreshState = .Refreshing
            }
            
        }
        
        
        
        
        
        
    }
    
//    结束刷新
    func endRefreshing() {
        refreshState = .Normal
    }
    
//    移除kvo
    
    deinit{
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
}
